package com.lyj.mp.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lyj.mp.domain.po.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;
import java.util.List;

@SpringBootTest
public class UserMapperTest2 {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelectByTerms() {
        // 查询出名字中带o的，存款大于等于1000元的人的id、username、info、balance字段
        // select id,username,info,balance from user where username like #{} and balance >= 1000;
        // 1、构建查询条件
        LambdaQueryWrapper<User> wrapper = new QueryWrapper<User>().lambda()
                .select(User::getId, User::getUsername,
                        User::getInfo, User::getBalance)
                .like(User::getUsername, "o")
                .ge(User::getBalance, 1000);
        // 2、查询
        List<User> users = userMapper.selectList(wrapper);
        System.out.println(users);
    }

    @Test
    public void testSelectByName() {
        // 更新用户名为jack的用户的余额为2000
        // update user set balance = 2000 where username = 'jack'
        // 1、要更新的数据
        User user = new User();
        user.setBalance(2000);
        // 2、更新的条件
        LambdaQueryWrapper<User> eq = new QueryWrapper<User>().lambda()
                .eq(User::getUsername, "jack");
        // 3、执行更新
        userMapper.update(user, eq);
    }

    @Test
    public void testUpdate() {
        // 需求: 更新id为1,2,4的用户的余额，扣200
        // update user set balance = balance - 200 where id in (1,2,4)
        // 1、更新条件
        List<Long> list = Arrays.asList(3L,4L);
        LambdaUpdateWrapper<User> id = new UpdateWrapper<User>().lambda()
                .setSql("balance = balance - 200")
                .in(User::getId, list);
        // 2、执行更新
        userMapper.update(null,id);
    }

    // 自定义sql
    @Test
    public void testCustomSqlUpdate(){
        // 1、更新条件
        List<Long> list = Arrays.asList(3L,4L);
        int amount = 100;
        // 2、定义条件
        QueryWrapper<User> wrapper = new QueryWrapper<User>()
                .in("id",list);
        // 3、调用自定义sql方法
        userMapper.updateBalanceByIds(wrapper,amount);
    }
}
